package com.browsesoft.resource;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;

import com.browsesoft.EntityManagerRMI;
import com.browsesoft.Server;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLTreeModel;
import com.browsesoft.user.Role;

/**
 * 
 */
public class RemoteFunctionTreeModel implements HTMLTreeModel {
	/**
	 * 功能树所对应的用户
	 */
	private Resource root = null;

	/**
	 * 拥有的资源
	 */
	public Collection resources = new LinkedList();

	/**
	 * 不拥有的资源
	 */
	public Collection notResources = new HashSet();

	public Collection allResources = new LinkedList();

	public RemoteFunctionTreeModel() {
	}

	/**
	 * 初始化model
	 * 
	 * @param request
	 *            请求
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		// User user = (User) request.getSession().getAttribute("loginUser");
		String userName = (String) request.getSession()
				.getAttribute("userName");
		// 装载根资源
		EntityManagerRMI entitymanager = Server.getEntityManagerRMI();
		root = entitymanager.getRoot();
		// Resource rt = entitymanager.getRoot();
		// String id = rt.getID();
		// LinkedList list = rt.getChildren();
		// Iterator iter = list.iterator();
		// while (iter.hasNext())
		// {
		// Resource res = (Resource) iter.next();
		// if (res.getType().equals("functiontree"))
		// {
		// root = res;
		// break;
		// }
		// }
		resources = this.getRes(userName);
		notResources = ResourceTool.getAllAncenstor(resources);
		this.allResources.clear();
		this.allResources.addAll(resources);
		this.allResources.addAll(notResources);
	}

	/**
	 * 得到资源
	 * 
	 * @return
	 * @throws Exception
	 */
	public Collection getRes(String userName) throws Exception {
		// String userName = (String) user.getAttributes().get("ename");
		LinkedList ls = Server.getEntityManagerRMI().getObjects(
				"com.browsesoft.resource.Resource");
		Collection rs = LicensePolicyTool.getRemoteRights(userName, ls);
		LinkedList link = ((BasicResource) Server.getEntityManagerRMI()
				.getRoot()).getSpecialResByType("role");
		Iterator iter = link.iterator();
		while (iter.hasNext()) {
			Role role = (Role) iter.next();
			LinkedList list = role.getUsers();
			if (isContains(list, userName)) {
				rs.addAll(LicensePolicyTool.getRemoteRights(role, ls));
			}
		}
		return rs;
	}

	private boolean isContains(Collection s, String userName) {
		Iterator iter = s.iterator();
		while (iter.hasNext()) {
			Resource item = (Resource) iter.next();
			Object ename = item.getAttributes().get("ename");
			if (ename.equals(userName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 处理用户请求
	 * 
	 * @param request
	 *            客户端请求
	 * @param response
	 *            响应
	 * @throws Exception
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	}

	/**
	 * 取得根结点
	 * 
	 * @return 根结点
	 * @throws Exception
	 */
	public Object getRootNode() throws Exception {
		return root;
	}

	/**
	 * 根据结点返回子结点
	 * 
	 * @param node
	 * @return
	 * @throws Exception
	 */
	public LinkedList getChildNodes(Object node) throws Exception {
		LinkedList children = new LinkedList(((Resource) node)
				.getChildrenByType("functiontree,function"));
		// 从子中过虑掉无权访问的节点
		retainAll(children, this.allResources);
		return children;
	}

	private boolean retainAll(Collection c, Collection cc) {
		boolean modified = false;
		Iterator e = c.iterator();
		while (e.hasNext()) {
			if (!isContains(cc, (Resource) e.next())) {
				e.remove();
				modified = true;
			}
		}
		return modified;
	}

	private boolean isContains(Collection s, Resource resource) {
		Iterator iter = s.iterator();
		while (iter.hasNext()) {
			Resource item = (Resource) iter.next();
			String id = item.getID();
			if (id.equals(resource.getID())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 根据结点返回结点的名称
	 * 
	 * @param node
	 *            结点
	 * @return 结点的名称
	 * @throws Exception
	 */
	public String getName(Object node) throws Exception {
		return (String) ((Resource) node).getAttributes().get("name");
	}

	/**
	 * 根据结点返回结点的id
	 * 
	 * @param node
	 *            结点
	 * @return 结点的名称
	 * @throws Exception
	 */
	public String getID(Object node) throws Exception {
		return ((Resource) node).getID();
	}

	/**
	 * 根据id找到结点对象
	 * 
	 * @param ID
	 *            对象id
	 * @return 结点对象
	 * @throws Exception
	 */
	public Object getObject(String ID) throws Exception {
		EntityManagerRMI entitymanager = Server.getEntityManagerRMI();
		return entitymanager.getObject(ID);
	}

	/**
	 * 根据结点返回结点的链接
	 * 
	 * @param node
	 *            结点
	 * @return 结点的链接
	 * @throws Exception
	 */
	public String getLink(Object node) throws Exception {
		return (String) ((Resource) node).getAttributes().get("link");
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @param c
	 *            组件
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 设置链接内容
	 * 
	 * @param nodeLink
	 *            链接
	 * @param modelNode
	 *            结点
	 * @throws Exception
	 */
	public void setContextNode(Element nodeLink, Object modelNode)
			throws Exception {
		// 得到链接的onclick属性
		String onclick = nodeLink.getAttribute("onclick");
		// 得到对应功能的id号
		String fid = ((BasicResource) modelNode).getID();
		// 替换onclick中的functionid
		onclick = onclick.replaceFirst("functionid=", "functionid=" + fid);
		// 设置onclick属性
		nodeLink.setAttribute("onclick", onclick);
	}

	/**
	 * 判断是否有子
	 * 
	 * @param obj
	 * @return boolean
	 */
	public boolean hasChilds(Object obj) {
		Resource res = (Resource) obj;
		return res.getChildren().hasNext();
	}

	/**
	 * 得到节点对应的图标
	 * 
	 * @param node
	 *            节点
	 * @return 图标
	 */
	public String getIcon(Object node) {
		return null;
	}
}